<?

//require_once(dirname(__FILE__) . '/../abstract/db.php');

class bf_db_postgresql extends bf_db {

	private $conn;

	public function __construct($options = array()) {
		$opts = array_merge(array(
			'host' => 'localhost',
			'port' => '5432',
			'database' => 'postgres',
			'user' => 'postgres',
			'password' => '',
			'log' => dirname(__FILE__) . '/../../../logs/db-postgresql-' . date('Y-m-d') . '.log',
			'logging' => 1,
		), $options);
		parent::__construct($opts);
	}

	public function escape($str) {
		return pg_escape_string($str);
	}

	public function connect() {
		$this->conn = @pg_connect(
			"host={$this->opts['host']}"
			. " port={$this->opts['port']}"
			. " dbname={$this->opts['database']}"
			. " user={$this->opts['user']}"
			. " password={$this->opts['password']}"
		);
		if (!$this->conn)
			$this->log_append("Couldn't connect to database server {$this->opts['host']}:{$this->opts['port']}");
	}

	public function disconnect() {
		if ($this->conn)
			@pg_close($this->conn);
	}

	public function is_connected() {
		return ($this->conn ? true : false);
	}

	public function get_true() {
		return 'true';
	}

	public function get_false() {
		return 'false';
	}

	public function is_true($value) {
		return preg_match('/^t/i', "$value");
	}

	public function is_false($value) {
		return preg_match('/^f/i', "$value");
	}

	protected function make_query($sql, $params = array()) {
		if ($this->opts['logging'] > 1)
			$this->log_append("SQL: $sql\nPARAMS: ".join(', ', $params)."\n");
		if (!($res = @pg_query_params($this->conn, $sql, $params)))
			$this->log_error();
		return $res;
	}

	public function fetch_all($res, $params = array()) {
		if (!($rows = @pg_fetch_all($res)))
			$rows = array();
		return $rows;
	}

	public function fetch_row($res) {
		return @pg_fetch_assoc($res);
	}

	public function fetch_column($res, $column = false) {
		$row = ($column ? @pg_fetch_assoc($res) : @pg_fetch_array($res));
		return ($column ? @$row[$column] : @$row[0]);
	}

	public function is_error() {
		return (@pg_last_error($this->conn) ? true : false);
	}

	public function get_error_text() {
		return @pg_last_error($this->conn);
	}

	public function get_debug_text() {
		return @pg_last_notice($this->conn);
	}

	public function start() {
		return $this->query('start transaction');
	}

	public function commit() {
		return $this->query('commit transaction');
	}

	public function rollback() {
		return $this->query('rollback transaction');
	}
}

?>